#include "animation.h"

//===============================================================
// Loads a new animation from the specified file.
//===============================================================
CAnimation::CAnimation(const char *szFileName, int nAnimations, int nFrames, float flFrameWidth, float flFrameHeight, float flSpeed)
	:	m_nFrames(nFrames), 
		m_nCount(nAnimations),
		m_flSpeed(flSpeed),
		m_nFrame(0),
		m_nAni(0),
		m_bRunning(true),
		m_nAniDir(0),
		m_nAniMode(LOOP_CONTINUOUS),
		m_flFrameWidth(flFrameWidth),
		m_flFrameHeight(flFrameHeight)
{
	m_pTexture = CTextureManager::Load(szFileName);
	if (!m_pTexture)
		return;

	m_flFrameTexWidth  = 1.0f / (m_pTexture->GetWidth() / flFrameWidth);
	m_flFrameTexHeight = 1.0f / (m_pTexture->GetHeight() / flFrameHeight);
}

//===============================================================
// Renders the animation to the specified size on screen.
//===============================================================
void CAnimation::Render(int nX, int nY)
{
	if (m_bRunning && m_nFrames > 1)
	{
		float flTime    = GetTickCount() / 1000.0f;
		float flElapsed = flTime - m_flLastFrame;

		if (flElapsed >= m_flSpeed) 
		{
			if (m_nAniMode == LOOP_ALTERNATE) 
			{
				if (m_nAniDir == 0) // -->>
				{
					m_nFrame++;
					if (m_nFrame >= m_nFrames)
					{
						m_nFrame = m_nFrames - 2;
						m_nAniDir = 1;
					}
				}
				else if (m_nAniDir = 1) // <<--
				{
					m_nFrame--;
					if (m_nFrame < 0)
					{
						m_nFrame = 1;
						m_nAniDir = 0;
					}
				}
			}
			else 
			{
				m_nFrame++;
				if (m_nFrame >= m_nFrames)
					m_nFrame = 0;
			}

			m_flLastFrame = flTime;
		}
	}

	m_pTexture->Bind();
	glColor3f(1.0f, 1.0f, 1.0f);

	glBegin(GL_QUADS);
		glTexCoord2f((m_nFrame * m_flFrameTexWidth), (m_nAni * m_flFrameTexHeight));
		glVertex2d(nX, nY);

		glTexCoord2f((m_nFrame * m_flFrameTexWidth) + m_flFrameTexWidth, (m_nAni * m_flFrameTexHeight));
		glVertex2d(nX + m_flFrameWidth, nY);

		glTexCoord2f((m_nFrame * m_flFrameTexWidth) + m_flFrameTexWidth, (m_nAni * m_flFrameTexHeight) + m_flFrameTexHeight);
		glVertex2d(nX + m_flFrameWidth, nY + m_flFrameHeight);

		glTexCoord2f((m_nFrame * m_flFrameTexWidth), (m_nAni * m_flFrameTexHeight) + m_flFrameTexHeight);
		glVertex2d(nX, nY + m_flFrameHeight);
	glEnd();
}
